﻿package 
{
	import flash.display.Bitmap;
	import flash.display.Sprite;	
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.text.TextField;
	import flash.ui.Keyboard;
	import org.papervision3d.cameras.Camera3D;
	import org.papervision3d.core.math.Number3D;
	import org.papervision3d.materials.BitmapMaterial;
	import org.papervision3d.materials.WireframeMaterial;
	import org.papervision3d.objects.primitives.Plane;
	import org.papervision3d.render.BasicRenderEngine;
	import org.papervision3d.scenes.Scene3D;
	import org.papervision3d.view.Viewport3D;
	import org.papervision3d.view.layer.ViewportLayer;	
	import org.papervision3d.view.layer.util.ViewportLayerSortMode;
	
	/*
	 * coded by moka 2009 / 06/ 20 
	 * name : moka's Keroro
	 */
	
	public class Main extends Sprite 
	{		
		private var scene:Scene3D;
		private var camera:Camera3D;
		private var viewport:Viewport3D;
		private var render:BasicRenderEngine;
		private var keroro:Keroro;
		private var floor:Plane;
		
		// 貼圖的紋理
		[Embed(source = 'krrMat.gif')]
		private var EmbeddedImage:Class;
		private var image:Bitmap;

		public function Main():void 
		{			
			// Class 類別隱式轉換成 Bitmap 類別
			image = new EmbeddedImage(); 
			
			// 設定場景不變形
			stage.scaleMode = "noScale"; 
			
			// Scene3D 用來組織場景母子關係樹狀架構
 			scene = new Scene3D();

			// Camera3D 為 3D 場景可視範圍設定
			camera = new Camera3D();
			camera.y = 250;
			
			// Viewport3D 用在呈現於 flash 場景(其類別繼承Sprite)
			viewport = addChild(new Viewport3D(640, 480)) as Viewport3D;		
			
			// 用以渲染 3D 場景之類別
			render = new BasicRenderEngine();
					
			// 分層渲染
			keroro = new Keroro(new BitmapMaterial(image.bitmapData));
			var vpl02:ViewportLayer = new ViewportLayer(viewport, keroro);			
			viewport.containerSprite.addLayer(vpl02);
			scene.addChild(keroro);
			
			floor = new Plane(new WireframeMaterial(0,0.3), 1000, 1000, 4, 4);
			var vpl01:ViewportLayer = new ViewportLayer(viewport, floor);	
			viewport.containerSprite.addLayer(vpl01);
			floor.rotationX = 90;
			scene.addChild(floor);
			
			viewport.containerSprite.sortMode = ViewportLayerSortMode.INDEX_SORT;
			vpl01.layerIndex = 1;
			vpl02.layerIndex = 2;
			
			// 註冊事件
			stage.addEventListener(Event.ENTER_FRAME, onProcess);	
			stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void {
				switch(e.keyCode) {
					case Keyboard.LEFT: keroro.rotationY -= 10;  break;
					case Keyboard.RIGHT:keroro.rotationY += 10;  break;
					case Keyboard.UP:   keroro.moveBackward(10); break;
					case Keyboard.DOWN: keroro.moveForward(10);  break;
				}				
			})

			// Moka's work 2009
			(addChild(new TextField()) as TextField).htmlText = "<font color='#FFFFFF'>Moka's work 2009</font>"; 
		}		

		private function onProcess(e:Event):void {	
			// 渲染 3D 場景
			render.renderScene(scene, camera, viewport);
		}
	}	
}